<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2022-03-08
 * Time: 20:54
 */

namespace plugin\thinkphp\common;



use ExAdmin\ui\support\Token;
use ExAdmin\ui\token\AuthException;
use plugin\thinkphp\Admin;
use ExAdmin\ui\component\navigation\menu\MenuItem;
use ExAdmin\ui\contract\SystemAbstract;
use ExAdmin\ui\response\Response;
use ExAdmin\ui\support\Arr;
use plugin\thinkphp\controller\AdminController;
use think\exception\HttpResponseException;


class System extends SystemAbstract
{
    /**
     * 网站名称
     * @return string
     */
    public function name(): ?string
    {
        return admin_sysconf('web_name');
    }

    /**
     * 网站logo
     * @return string
     */
    public function logo(): ?string
    {
        return admin_sysconf('web_logo');
    }
    /**
     * 网站logo跳转地址
     * @return string
     */
    public function logoHref(): ?string
    {
        return plugin()->thinkphp->config('route.prefix');
    }
    /**
     * 头部导航右侧
     * @return array
     */
    public function navbarRight(): array
    {
        return [];
    }
    
    /**
     * 头部点击用户信息下拉菜单
     * @return array
     */
    public function adminDropdown(): array
    {
       return [
           MenuItem::create()->content(admin_trans('admin.user_info'))
               ->modal([AdminController::class,'editInfo'],['id'=>Admin::id()]) ,
           MenuItem::create()->content(admin_trans('admin.update_password'))
               ->modal([AdminController::class,'updatePassword'],['id'=>Admin::id()]),
       ];
    }

    /**
     * 用户信息
     * @return array
     */
    public function userInfo(): array
    {
        try{
            Token::auth();
        }catch (AuthException $exception){
            throw new HttpResponseException(json(['message' => $exception->getMessage(), 'code' => $exception->getCode()], 401));
        }
        return Admin::user()
            ->visible(['id','nickname','avatar'])
            ->toArray();
    }

    /**
     * 菜单
     * @return array
     */
    public function menu(): array
    {
        return Arr::tree(admin_menu()->all());
    }
    /**
     * 上传写入数据库
     * @param $data 上传入库数据
     * @return Response
     */
    public function upload($data): Response
    {
        $model = plugin()->thinkphp->config('database.attachment_model');
        if(!$model::where($data)->find()){
            $data['uploader_id'] = Admin::id();
            $model::create($data);
        }
        return Response::success();
    }


    /**
     * 验证权限
     * @param $class 类名
     * @param $function 方法
     * @param $method 请求method
     * @return bool
     */
    public function checkPermissions($class, $function, $method): bool
    {
        return Admin::check($class, $function, $method);
    }
}
